package com.youlu.campus.website.service.impl;

import com.youlu.campus.common.exception.BusinessException;
import com.youlu.campus.website.common.enums.PlatformType;
import com.youlu.campus.website.entity.Carousel;
import com.youlu.campus.website.entity.CarouselPageQuery;
import com.youlu.campus.website.repositories.CarouselRepository;
import com.youlu.campus.website.service.CarouselService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 轮播图服务实现类
 */
@Service
public class CarouselServiceImpl implements CarouselService {

    @Autowired
    private CarouselRepository carouselRepository;


    @Resource(name = "websiteMongoTemplate")
    private MongoTemplate mongoTemplate;

    @Override
    public Carousel save(Carousel carousel) {
        if (StringUtils.isNotBlank(carousel.getId())) {
            carousel.setUpdateTime(LocalDateTime.now());
        } else {
            carousel.setId(null);
            carousel.setCreateTime(LocalDateTime.now());
        }
        return carouselRepository.save(carousel);
    }

    @Override
    public void deleteCarousel(String id) {
        if (!carouselRepository.existsById(id)) {
            return;
        }
        carouselRepository.deleteById(id);
    }

    @Override
    public Carousel getCarouselById(String id) {
        return carouselRepository.findById(id)
                .orElseThrow(() -> new BusinessException("轮播图不存在"));
    }

    @Override
    public Page<Carousel> findByPage(CarouselPageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getTitle())) {
            query.addCriteria(Criteria.where("title").regex(pageQuery.getTitle(), "i"));
        }
        if (pageQuery.getPlatform() != null) {
            query.addCriteria(Criteria.where("platform").is(pageQuery.getPlatform()));
        }
        if (pageQuery.getStatus() != null) {
            query.addCriteria(Criteria.where("status").is(pageQuery.getStatus()));
        }
        if (pageQuery.getType() != null) {
            query.addCriteria(Criteria.where("type").in(pageQuery.getType()));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, Carousel.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<Carousel> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = mongoTemplate.find(query, Carousel.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }

    @Override
    public List<Carousel> getEnabledCarouselsByPlatform(PlatformType platform) {
        return carouselRepository.findByPlatformAndStatusOrderBySortOrderAsc(platform, 1);
    }

}
